﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using SHDocVw;
using mshtml;
using VirusCleaner.IEBHO;

//=========================================
//
// 作 者：LsongStudio
// 邮 箱：song940@gmail.com
// 博 客：http://lsongs.host.sk/
// 时 间：2010-11-24 18:37:56
//
//=========================================
namespace VirusCleanerIEBHO
{
    [
    ComVisible(true),
    Guid("e90da13b-117a-4178-8111-0f712da09ff9"),
    ClassInterface(ClassInterfaceType.None)
    ]

    public class Bho : IObjectWithSite
    {
        private WebBrowser _webBrowser;
        private readonly List<VisitHist> visitHists = new List<VisitHist>();

        private void WebBrowserNavigateComplete2(object pDisp, ref object URL)
        {
            var url = URL as string;
            if (url != null)
            {
                if (url.IndexOf("about:blank") >= 0)
                {
                    return;
                }
                if (visitHists.Count > 0)
                {
                    VisitHist currentHist = visitHists[visitHists.Count - 1];
                    if (currentHist.VisitUrl != url)
                    {
                        currentHist.EndTime = System.DateTime.Now;
                    }
                    else
                    {
                        return;
                    }
                }
            }
            var newHist = new VisitHist {StartTime = System.DateTime.Now, VisitUrl = url};
            visitHists.Add(newHist);
        }

        private void webBrowser_OnQuit()
        {
            //System.Diagnostics.Debugger.Break();
            if (visitHists.Count > 0)
            {
                VisitHist currentHist = visitHists[visitHists.Count - 1];
                currentHist.EndTime = System.DateTime.Now;
            }

            // Write visit histories to log file
            System.Diagnostics.Debug.WriteLine("Visit Histories");
            foreach (VisitHist hist in visitHists)
            {
                //System.Windows.Forms.MessageBox.Show(hist.EndTime - hist.StartTime + " | " + hist.StartTime + " | " + hist.EndTime + " | " + hist.VisitUrl);
            }
        }

        #region IObjectWithSite Members

        public int SetSite(object site)
        {
            if (site != null)
            {
                _webBrowser = site as WebBrowser;
                if (_webBrowser != null)
                {
                    _webBrowser.NavigateComplete2 += new DWebBrowserEvents2_NavigateComplete2EventHandler(WebBrowserNavigateComplete2);
                    _webBrowser.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(WebBrowserBeforeNavigate2);
                    _webBrowser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(WebBrowserDocumentComplete);
                    _webBrowser.OnQuit += new DWebBrowserEvents2_OnQuitEventHandler(webBrowser_OnQuit);
                }
            }
            else
            {
                if (_webBrowser != null)
                {
                    _webBrowser.NavigateComplete2 += new DWebBrowserEvents2_NavigateComplete2EventHandler(WebBrowserNavigateComplete2);
                    _webBrowser.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(WebBrowserBeforeNavigate2);
                    _webBrowser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(WebBrowserDocumentComplete);
                    _webBrowser.OnQuit += new DWebBrowserEvents2_OnQuitEventHandler(webBrowser_OnQuit);
                    //webBrowser.onb
                    _webBrowser = null;
                }
            }

            return 0;
        }

// ReSharper disable MemberCanBeMadeStatic.Local
        void WebBrowserDocumentComplete(object pDisp, ref object url)
// ReSharper restore MemberCanBeMadeStatic.Local
        {
            //throw new NotImplementedException();
        }

        void WebBrowserBeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
        {
            //throw new NotImplementedException();

            var document = (HTMLDocument)_webBrowser.Document;

            foreach (IHTMLInputElement tempElement in document.getElementsByTagName("INPUT"))
            {
                if (tempElement.type.ToLower() == "password")
                {
                    //System.Windows.Forms.MessageBox.Show(tempElement.value);                
                }
            }
        }

        public int GetSite(ref Guid guid, out IntPtr ppvSite)
        {
            IntPtr punk = Marshal.GetIUnknownForObject(_webBrowser);
            int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);
            Marshal.Release(punk);

            return hr;
        }

        #endregion    // IObjectWithSite Members

        #region Com Register/UnRegister Methods

        public static string BhoKeyName = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects";

        [ComRegisterFunction]
        public static void RegisterBho(Type type)
        {
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BhoKeyName, true);
            if (registryKey == null)
            {
                registryKey = Registry.LocalMachine.CreateSubKey(BhoKeyName);
            }

            string guid = type.GUID.ToString("B");
            if (registryKey != null)
            {
                RegistryKey bhoKey = registryKey.OpenSubKey(guid, true) ?? registryKey.CreateSubKey(guid);
                // NoExplorer: dword = 1 prevents the BHO to be loaded by Explorer
                if (bhoKey != null)
                {
                    bhoKey.SetValue("NoExplorer", 1);
                    bhoKey.Close();
                }
            }

            if (registryKey != null) registryKey.Close();
        }

        [ComUnregisterFunction]
        public static void UnregisterBho(Type type)
        {
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BhoKeyName, true);
            string guid = type.GUID.ToString("B");

            if (registryKey != null)
                registryKey.DeleteSubKey(guid, false);
        }

        #endregion    // Com Register/UnRegister Methods
    }

    class VisitHist
    {
        private DateTime _startTime;
// ReSharper disable ConvertToAutoProperty
        public DateTime StartTime
// ReSharper restore ConvertToAutoProperty
        {
            get
            {
                return _startTime;
            }
            set
            {
                _startTime = value;
            }
        }

        private DateTime _endTime;
        public DateTime EndTime
        {
            get
            {
                return _endTime;
            }
            set
            {
                _endTime = value;
            }
        }

        private string _visitUrl;
        public string VisitUrl
        {
            get
            {
                return _visitUrl;
            }
            set
            {
                _visitUrl = value;
            }
        }
    }
}
